<template>
  <div ref="dom"></div>
</template>

<script>
import echarts from 'echarts'
import { on, off } from '@/libs/tools'

export default {
  name: 'timeLine',
  data () {
    return {
      data: [],
      dom: null,
      now: +new Date(1997, 9, 3),
      oneDay: 24 * 3600 * 1000,
      value: Math.random() * 1000,
      timer: null
    }
  },
  methods: {
    resize () {
      this.dom.resize()
    },
    randomData () {
      this.now = new Date(+this.now + this.oneDay)
      this.value = Math.random() * 100000 + Math.random() * 100000 * Math.random() - Math.random() * 1000
      return {
        name: this.now.toString(),
        value: [
          [this.now.getFullYear(), this.now.getMonth() + 1, this.now.getDate()].join('/'),
          Math.round(this.value)
        ]
      }
    },
    getData () {
      for (var i = 0; i < 5; i++) {
         this.data.shift()
        this.data.push(this.randomData())
      }

      this.dom.setOption({
        series: [{
          data: this.data
        }]
      })
    }

  },
  mounted () {
    debugger
    for (var i = 0; i < 30; i++) {
      this.data.push(this.randomData())
    }
    const option = {
      title: {
        text: '动态数据 + 时间坐标轴'
      },
      tooltip: {
        trigger: 'axis',
        formatter: function (params) {
          params = params[0]
          var date = new Date(params.name)
          return date.getDate() + '/' + (date.getMonth() + 1) + '/' + date.getFullYear() + ' : ' + params.value[1]
        },
        axisPointer: {
          animation: false
        }
      },
      xAxis: {
        type: 'time',
        splitLine: {
          show: false
        }
      },
      yAxis: {
        type: 'value',
        boundaryGap: [0, '100%'],
        splitLine: {
          show: false
        }
      },
      series: [{
        name: '模拟数据',
        type: 'line',
        showSymbol: false,
        hoverAnimation: false,
        data: this.data
      }]
    }
    this.$nextTick(() => {
      this.dom = echarts.init(this.$refs.dom)
      this.dom.setOption(option)
      on(window, 'resize', this.resize)
    })
    this.timer = setInterval(this.getData, 1000)
  },
  beforeDestroy () {
    off(window, 'resize', this.resize)
    clearInterval(this.timer)
  }
}
</script>
